import axios from 'axios'
import { Toast } from 'vant';
import router from '../router'
const baseURL = 'http://localhost:8080/'
const version = 'api/v1'
//生成实例化对象
const fetch = axios.create({
    baseURL:baseURL+version,
    timeout: 5000,
    headers: {}
});

//拦截器
// Add a request interceptor
fetch.interceptors.request.use(function (config) {
    //有一些需要token才能吊通接口
    config.headers.Authorization=localStorage.getItem('token')
    return config;
}, function (error) {
    return Promise.reject(error);
});

// Add a response interceptor
fetch.interceptors.response.use(function (response) {
    var res=null
    if (response.status==200){
        if(response.data&&response.data.err==0){
            res = response.data.data
            //当err==-1说明token无效或者过期了
        }else if(response.data&&response.data.err==-1){
            router.replace('/login')
        } else {
            Toast.fail(response.data.msg)
        }
    }
    return  res
}, function (error) {
    return Promise.reject(error);
});
export default fetch